import React, {Component} from 'react';
import {LogIn as LogInOption} from "../../api/api";
import {instance} from "../../api/base";
import {Button, Form, Input} from 'element-react'


class LogInPage extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            form: {
                pass: '123456',
                userId: 'root',
                time: 4000
            },
            rules: {
                pass: [
                    {required: true, message: '请输入密码', trigger: 'blur'},
                ],
                userId: [
                    {required: true, message: '请输入管理员Id', trigger: 'blur'},
                ]
            }
        };
    }

    handleSubmit(e) {
        e.preventDefault();
        this.refs.form.validate((valid) => {
            if (valid) {
                this.LogIn();
            } else {
                console.log('error submit!!');
                return false;
            }
        });
    }

    handleReset(e) {
        e.preventDefault();
        this.refs.form.resetFields();
    }

    onChange(key, value) {
        this.setState({
            form: Object.assign({}, this.state.form, {[key]: value})
        });
    }

    LogIn = (e) => {
        const params = {
            password: this.state.form.pass,
            time: this.state.form.time,
            administrator_id: this.state.form.userId
        };
        console.log(params);
        LogInOption(params).then(x => {
            console.log(x, 999999999);
            instance.defaults.headers.token = x.result.token;
            window.localStorage.setItem('token', x.result.token)
        }).catch(x => {
            console.log(x)

        })
    };

    render() {
        return (
            <div>
                <Form ref="form" model={this.state.form} rules={this.state.rules} labelWidth="100"
                      className="logIn-form">
                    <h1>个人网站后台管理登录页</h1>

                    <Form.Item label="用户账号" prop="userId">
                        <Input value={this.state.form.userId}
                               onChange={this.onChange.bind(this, 'userId')} autoComplete="off"/>
                    </Form.Item>
                    <Form.Item label="密码" prop="pass">
                        <Input type="password" value={this.state.form.pass} onChange={this.onChange.bind(this, 'pass')}
                               autoComplete="off"/>
                    </Form.Item>
                    <Form.Item>
                        <Button type="primary" onClick={this.handleSubmit.bind(this)}>提交</Button>
                        <Button onClick={this.handleReset.bind(this)}>重置</Button>
                    </Form.Item>
                </Form>
            </div>
        );
    }


}

export default LogInPage;